"use strict";

/**
 * 服务器列表控制器
 */
angular.module("app").controller("serverListCtrl", function($scope, $http, $location) {

	/**
	 * 服务器列表
	 */
	$scope.serverList = {
		datas  :  [],
		find   :  function(id){
			for(var i = 0; i < this.datas.length; i++){
				var server = this.datas[i];
				if(server.id == id){
					return i;
				}
			}
			return -1;
		},
		remove :  function(id){
			var targetIdx = this.find(id);
			if(targetIdx > -1){
				this.datas.splice(targetIdx, 1);
			}
		},
		init : function(){
			$http.get("/server/list",{
				cache	:	true
			}).success(function(d) {
				if(d.success){
					$scope.serverList.datas = d.ret.serverList;
				}
			});
		}
	};
	$scope.serverList.init();
	
	/**
	 * 服务器添加模型
	 */
	$scope.serverAddModel = {
		data : null,
		init : function(){
			this.data = {
				host		:	"",
				port		:	"22",
				username	:	"",
				password	:	"",
				rootdir		:	"",
				filter		:	".sh;.bat;.properties;.xml;.txt;.log;.html;.html;.js;.css;.key;.vm;",
				description	:	""
			}
		},
		submit : function(){
			$http.post("/server/dadd", $scope.serverAddModel.data).success(function(d){
				if(d.success){
					$scope.serverList.datas.push(d.ret.server);
					$scope.serverAddModel.init();
					
					$("#server_add_modal").modal('hide');
				}
			});
		}
	}

	/**
	 * 服务器添加对象模型初始化
	 */
	$scope.serverAddModel.init();
	
	/**
	 * 服务器编辑模型
	 */
	$scope.serverEditModel = {
		data : {},
		attach : function(serverId){
			var serverIdx = $scope.serverList.find(serverId);
			this.data = $scope.serverList.datas[serverIdx];
		},
		openDialog : function(serverId){		
			$scope.serverEditModel.attach(serverId);
			$("#server_edit_modal").modal("show");
		},
		submit : function(){
			$http.post("/server/dedit", $scope.serverEditModel.data).success(function(d){
				if(d.success){
					
					$("#server_edit_modal").modal("hide");
				}
			});
		}
	}
	
	/**
	 * 删除服务器节点
	 */
	$scope.delServer = function(serverId){
		$http.get("/server/ddel?sid=" + serverId).success(function(d){
			if(d.success){
				$scope.serverList.remove(serverId);
			}
		});
	}
	
	/**
	 * 配置服务器节点
	 */
	$scope.confServer = function(serverId){
		$location.path("/config/list/" + serverId);
	}
});
